class UserController < ApplicationController
  auto_complete_for :thing,:title
  def index
    
  end

  def view
    
    logger.debug "======the user id #{params[:id]}"
      
    @user = User.find(params[:id])
    @user_lists = User.find(:all,:order=>"created_at desc",:limit=>10)
    @top_things = Thing.find(:all,:order=>"created_at desc",:limit=>10)

    created_times = UserThing.find(:all,:order=>"updated_at asc",:conditions=>["MONTH(updated_at)=? and YEAR(updated_at)=? and user_id = ?",Time.now.month,Time.now.year,@user.id])
    array_a = ""
    for array_tmp in created_times

      if array_a.index(array_tmp.updated_at.day.to_s).nil?
        array_a << array_tmp.updated_at.day.to_s + ','
      end
    end
    array_a = array_a[0..array_a.size-2]
    @array_a =<<-eol
     #{array_a}
    eol
     
    options ={:page=>params[:page],:per_page=>5}
    user_id = User.find(params[:id])
    #@things = Thing.paginate_by_sql(["select title,tu.updated_at from(select user_id,thing_id,updated_at from user_things where user_id=?)tu  left join things on thing_id = things.id",user_id],options)
    @things = Thing.paginate_by_sql(["SELECT t1.id, t1.title, t2.updated_at FROM things t1, user_things t2, users t3 WHERE (t3.id = ?) AND (t2.user_id = t3.id) AND (t1.id = t2.thing_id)", user_id], options)
    
  end
  
  def edit
    @user = User.find(params[:id])
    @user_profile = UserProfile.find_by_user(params[:id]);
  end
  
  def things_day
    @user = User.find(params[:id])
    year = params[:year]
    month = params[:month]
    created_times = UserThing.find(:all,:order=>"updated_at asc",:conditions=>["MONTH(updated_at)=? and YEAR(updated_at)=? and user_id = ?",month,year,@user.id])
    array_a = ""
    for array_tmp in created_times
      if array_a.index(array_tmp.updated_at.day.to_s).nil?
        array_a <<  array_tmp.updated_at.day.to_s + ','
      end
    end
    array_a = array_a[0..array_a.size-2]
    array_a =<<-eol
       #{array_a}
    eol
    render :text=>array_a
  end
  
  def add_thing
    
    logger.debug "======the thing #{params[:thing_id]}"
    
    u_t = UserThing.new()
    u_t.user_id = current_user.id
    u_t.thing_id = params[:thing_id]
    if u_t.save
      redirect_to :action => 'view', :id => current_user.id
    end      
  end

end
